<html>
<head>

<title>Groovy Goodness: Transforming Reader Input to Writer Output</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Transforming Reader Input to Writer Output</h3>

<div class="post">
<p>With Groovy we can immediately transform the input from a <code>Reader</code> object(like a file, URL or other input type) to a <code>Writer</code> object (like a file, URL or other output type). Groovy adds the <code>transformLine(Writer, Closure)</code> and <code>transformChar(Writer, Closure)</code> methods to the <code>Reader</code> class. We need to pass the <code>Writer</code> object that will contain the transformed output as the first argument. The second argument is a closure with the rules for the transformation that needs to be applied.</p>
<pre class="brush:groovy">
def reader = new StringReader('''\
Groovy's support
for transforming reader input to writer output.
''')

def writer = new StringWriter()

reader.transformLine(writer) { line -&gt;  
    if (line.matches(~/^Groovy.*/)) {
        line = '&gt;&gt;' + line.replaceAll('Groovy', 'GROOVY') + '&lt;&lt; '
    }
    line
}

def resultTransformLine = writer.toString()

reader = new StringReader(resultTransformLine)
writer = new StringWriter()
reader.transformChar(writer) { ch -&gt;
    ch in ['\n', '\r'] ? '' : ch
}

assert writer.toString() == "&gt;&gt;GROOVY's support&lt;&lt; for transforming reader input to writer output."
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>